import org.apache.log4j.Logger;

import java.io.*;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;


/**
 * Created by aleks_000 on 14.12.13.
 */
public class CharStatisticsAnalyzer {
    private static final Logger LOGGER = Logger.getLogger(CharStatisticsAnalyzer.class);


    SortedMap<Character, Double> analyze(Reader reader) throws IOException {
        if (reader == null) {
            throw new NullPointerException();
        }
        LOGGER.info("Create a BufferedReader for incoming reader");
        BufferedReader bufferedReader = new BufferedReader(reader);
        String currentString = null;
        SortedMap<Character, Double> statisticsMap = new TreeMap<Character, Double>();
        int totalCount = 0;
        while ((currentString = bufferedReader.readLine()) != null) {
            LOGGER.info(String.format("Read line. Current line: \"%s\"", currentString));
            for (int i = 0; i < currentString.length(); i++) {
                Character currentCharacter = currentString.charAt(i);
                LOGGER.info(String.format("Get current character in the line. Current character: %c", currentCharacter));
                double currentCount = 0;
                if (statisticsMap.containsKey(currentCharacter)) {
                    LOGGER.warn(String.format("Collection already contains %c", currentCharacter));
                    currentCount = statisticsMap.get(currentCharacter);
                }
                currentCount += 1;
                LOGGER.info(String.format("Increase current character count. Current count: %f", currentCount));
                statisticsMap.put(currentCharacter, currentCount);
            }
            // add end-of-line symbol
            totalCount += currentString.length();
        }

        LOGGER.info(String.format("Total count of symbols: %d", totalCount));
        for (Map.Entry<Character, Double> entry : statisticsMap.entrySet()) {
            entry.setValue(entry.getValue() / totalCount);
        }

        return statisticsMap;
    }

    public SortedMap<Character, Double> analyze(String fileName) throws IOException {
        if (fileName == null) {
            throw new NullPointerException();
        }
        LOGGER.info(String.format("Try create a FileReader with file \"%s\"", fileName));
        FileReader reader = new FileReader(fileName);
        LOGGER.info("Reader successfully created");
        LOGGER.info("Start analyzing...");
        return analyze(reader);
    }
}
